package com.example.springsecurity.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

import java.util.ArrayList;
import java.util.Collection;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig {
    
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(authorize -> authorize.anyRequest().authenticated())
                .formLogin(form -> {
                    form.loginPage("/login").permitAll()//无序权限即可访问当前页面
                            .usernameParameter("username")
                            .passwordParameter("password")
                            .failureUrl("/login?error")//校验失败时跳转的地址，默认值是error
                            .successHandler(new MyAuthenticationSuccessHandler())//认证成功时的处理
                            .failureHandler(new MyAuthenticationFailureHandler())//认证失败时的处理
                    ;
                })
//                .formLogin(Customizer.withDefaults())
//                .httpBasic(Customizer.withDefaults())
        ;

        http.csrf(csrf -> csrf.disable());
        return http.build();
    }

//    @Bean
//    public UserDetailsService userDetailsService() {
//        // 创建基于内存的用户信息管理器
//        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
//        // 使用manager管理UserDetails对象
//        manager.createUser(
//                User.withDefaultPasswordEncoder().username("admin").password("123456").roles("USER").build()
//        );
//        return manager;
//    }
public static void main(String[] args) {
    UserDetails build = User.withDefaultPasswordEncoder().username("admin").password("123456").roles("USER").build();
    System.out.println(build.getPassword());
}
}
